﻿
///数组拓展

Array.prototype.where = function (predicate) {
    var arr = this;
    var retArr = [];
    for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        if (predicate(item)) {
            retArr.push(item);
        }
    }
    return retArr;
};
Array.prototype.select = function (selector) {
    var arr = this;
    var retArr = [];
    for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        retArr.push(selector(item));
    }
    return retArr;
};
Array.prototype.first = function (predicate) {
    var arr = this;
    for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        if (predicate(item)) {
            return item;
        }
    }
    return null;
};
Array.prototype.any = function (predicate) {
    var arr = this;
    var retArr = [];
    for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        if (predicate(item)) {
            return true;
        }
    }
    return false;
};
Array.prototype.pushRange = function (items) {
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        this.push(item);
    }
};
Array.prototype.each = function (action) {
    for (var i = 0; i < this.length; i++) {
        var item = this[i];
        action(item);
    }
};
Array.prototype.sortBy = function (keySelector, rev) {
    /*
     *此方法返回一个新对象 
     */
    var arr = [];
    for (var i = 0; i < this.length; i++) {
        arr.push(this[i]);
    }

    //第二个参数没有传递 默认升序排列
    rev = rev !== undefined && rev !== false;

    var compare = function (a, b) {
        a = keySelector(a);
        b = keySelector(b);

        if (rev)
            return b - a;
        else
            return a - b;
    }

    arr.sort(compare);
    return arr;
}
Array.prototype.orderBy = function (keySelector) {
    return this.sortBy(keySelector, false);
}
Array.prototype.orderByDesc = function (keySelector) {
    return this.sortBy(keySelector, true);
}
Array.prototype.groupBy = function (keySelector) {
    var arr = this;
    var ret = {};
    for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        var key = keySelector(item);
        var group;
        if (key in ret) {
            group = ret[key];
        }
        else {
            group = [];
            ret[key] = group;
        }

        group.push(item);
    }

    return ret;
}